import { useEffect, useRef, useState } from "react";
import MindMap from "simple-mind-map";
import Themes from "simple-mind-map-plugin-themes";
import RichText from "simple-mind-map/src/plugins/RichText.js";
import Export from "simple-mind-map/src/plugins/Export.js";
import Drag from "simple-mind-map/src/plugins/Drag.js";
import SelectPlugin from "simple-mind-map/src/plugins/Select.js";
import AssociativeLine from "simple-mind-map/src/plugins/AssociativeLine.js";
import KeyboardNavigation from "simple-mind-map/src/plugins/KeyboardNavigation.js";
import MiniMap from "simple-mind-map/src/plugins/MiniMap.js";
import Watermark from "simple-mind-map/src/plugins/Watermark.js";
import TouchEvent from "simple-mind-map/src/plugins/TouchEvent.js";
import NodeImgAdjust from "simple-mind-map/src/plugins/NodeImgAdjust.js";
import Search from "simple-mind-map/src/plugins/Search.js";
import Painter from "simple-mind-map/src/plugins/Painter.js";
import Scrollbar from "simple-mind-map/src/plugins/Scrollbar.js";
import Formula from "simple-mind-map/src/plugins/Formula.js";
import Cooperate from "simple-mind-map/src/plugins/Cooperate.js";
import RainbowLines from "simple-mind-map/src/plugins/RainbowLines.js";
import Demonstrate from "simple-mind-map/src/plugins/Demonstrate.js";
import OuterFrame from "simple-mind-map/src/plugins/OuterFrame.js";
import MindMapLayoutPro from "simple-mind-map/src/plugins/MindMapLayoutPro.js";
import type { SelectProps } from "antd";
import {
  Layout,
  Button,
  Tooltip,
  Select,
  Divider,
  theme,
  ColorPicker,
  message,
  Modal,
} from "antd";
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  UndoOutlined,
  RedoOutlined,
  SaveOutlined,
  ExportOutlined,
  PictureOutlined,
  BgColorsOutlined,
  FontSizeOutlined,
  BoldOutlined,
  ItalicOutlined,
  UnderlineOutlined,
  AlignLeftOutlined,
  AlignCenterOutlined,
  AlignRightOutlined,
  BranchesOutlined,
  NodeIndexOutlined,
  SearchOutlined,
  SettingOutlined,
  DragOutlined,
} from "@ant-design/icons";
import { customThemes } from "./themes";
import "./App.css";
import "./simpleMindMap.esm.css";
const { Header, Content } = Layout;

// 注册主题
Themes.init(MindMap);
Object.entries(customThemes).forEach(([name, config]) => {
  // @ts-ignore
  MindMap.defineTheme(name, config);
});

// 注册插件
MindMap.usePlugin(RichText);
MindMap.usePlugin(Export);
MindMap.usePlugin(Drag);
MindMap.usePlugin(SelectPlugin);
MindMap.usePlugin(AssociativeLine);
MindMap.usePlugin(KeyboardNavigation);
MindMap.usePlugin(MiniMap);
MindMap.usePlugin(Watermark);
MindMap.usePlugin(TouchEvent);
MindMap.usePlugin(NodeImgAdjust);
MindMap.usePlugin(Search);
MindMap.usePlugin(Painter);
MindMap.usePlugin(Scrollbar);
MindMap.usePlugin(Formula);
MindMap.usePlugin(Cooperate);
MindMap.usePlugin(RainbowLines);
MindMap.usePlugin(Demonstrate);
MindMap.usePlugin(OuterFrame);
MindMap.usePlugin(MindMapLayoutPro);

const layouts: SelectProps["options"] = [
  { label: "思维导图", value: "mindMap" },
  { label: "逻辑结构图", value: "logicalStructure" },
  { label: "组织结构图", value: "organizationStructure" },
  { label: "目录组织图", value: "catalogOrganization" },
  { label: "时间轴", value: "timeline" },
  { label: "时间轴2", value: "timeline2" },
  { label: "鱼骨图", value: "fishbone" },
];

const themes: SelectProps["options"] = [
  {
    label: "专业商务",
    options: [
      { label: "XMind风格", value: "xmind" },
      { label: "Word风格", value: "word" },
      { label: "知犀风格", value: "zhixi" },
      { label: "极简黑白", value: "minimal" },
      { label: "经典专业", value: "classic" },
      { label: "企业蓝", value: "enterprise" },
      { label: "商务专业", value: "businessPro" },
      { label: "科技白", value: "techWhite" },
    ],
  },
  {
    label: "创意特色",
    options: [
      { label: "卡通风格", value: "cartoon" },
      { label: "粉笔风格", value: "chalk" },
      { label: "手绘风格", value: "handdrawn" },
      { label: "霓虹风格", value: "neon" },
      { label: "水彩风格", value: "watercolor" },
    ],
  },
  {
    label: "活力多彩",
    options: [
      { label: "清新绿", value: "freshGreen" },
      { label: "活力橙", value: "energeticOrange" },
      { label: "商务蓝", value: "businessBlue" },
      { label: "科技紫", value: "techPurple" },
      { label: "优雅金", value: "elegantGold" },
    ],
  },
  {
    label: "现代简约",
    options: [
      { label: "现代简约", value: "modernSimple" },
      { label: "科技蓝调", value: "techBlue" },
      { label: "暖色商务", value: "warmBusiness" },
      { label: "自然绿意", value: "naturalGreen" },
    ],
  },
  {
    label: "特色主题",
    options: [
      { label: "深色专业", value: "darkPro" },
      { label: "自然棕", value: "naturalBrown" },
    ],
  },
];

const exportFormats = [
  { label: "PNG图片", value: "png" },
  { label: "SVG矢量图", value: "svg" },
  { label: "PDF文档", value: "pdf" },
  { label: "Markdown", value: "md" },
  { label: "JSON数据", value: "json" },
];

function App() {
  const containerRef = useRef<HTMLDivElement>(null);
  const mindMapRef = useRef<any>(null);
  const [currentLayout, setCurrentLayout] = useState("mindMap");
  const [currentTheme, setCurrentTheme] = useState("default");
  const [currentAction, setCurrentAction] = useState<"zoom" | "move">("move");
  const { token } = theme.useToken();
  const [messageApi, contextHolder] = message.useMessage();
  const [exportModalVisible, setExportModalVisible] = useState(false);
  const [exportFormat, setExportFormat] = useState("png");

  const handleWheel = (e: WheelEvent) => {
    if (e.ctrlKey) {
      e.preventDefault();
      if (!mindMapRef.current || !mindMapRef.current.view) return;

      const delta = e.deltaY < 0 ? 0.1 : -0.1;
      const currentScale = mindMapRef.current.view.scale || 1;
      const newScale = Math.max(0.1, Math.min(4, currentScale + delta));
      mindMapRef.current.view.scale = newScale;
      mindMapRef.current.render();
    }
  };

  useEffect(() => {
    if (!containerRef.current) return;

    const mindMap = new MindMap({
      el: containerRef.current,
      data: {
        data: {
          text: "根节点",
        },
        children: [
          {
            data: {
              text: "二级节点",
            },
            children: [],
          },
          {
            data: {
              text: "二级节点",
            },
            children: [],
          },
        ],
      },
      layout: currentLayout,
      theme: currentTheme,
      themeConfig:
        customThemes[currentTheme as keyof typeof customThemes] || {},
      mousewheelAction: currentAction,
      initRootNodePosition: ["center", "center"],
      viewCenter: true,
      fit: true,
    });

    mindMapRef.current = mindMap;

    containerRef.current.addEventListener("wheel", handleWheel, {
      passive: false,
    });

    mindMap.on("mounted", () => {
      mindMap.view.reset();
      mindMap.view.setScale(1);
      mindMap.render();
    });

    return () => {
      containerRef.current?.removeEventListener("wheel", handleWheel);
      mindMap.destroy();
    };
  }, [currentLayout, currentTheme, currentAction]);

  const handleZoomIn = () => {
    if (!mindMapRef.current || !mindMapRef.current.view) return;
    const currentScale = mindMapRef.current.view.scale;
    const newScale = Math.min(4, currentScale + 0.1);
    mindMapRef.current.view.scale = newScale;
    mindMapRef.current.render();
  };

  const handleZoomOut = () => {
    if (!mindMapRef.current || !mindMapRef.current.view) return;
    const currentScale = mindMapRef.current.view.scale;
    const newScale = Math.max(0.1, currentScale - 0.1);
    mindMapRef.current.view.scale = newScale;
    mindMapRef.current.render();
  };

  const handleUndo = () => {
    mindMapRef.current?.undo();
  };

  const handleRedo = () => {
    mindMapRef.current?.redo();
  };

  const handleSave = () => {
    const data = mindMapRef.current?.getData();
    localStorage.setItem("mindMapData", JSON.stringify(data));
    messageApi.success("保存成功");
  };

  const handleExport = async () => {
    try {
      const data = await mindMapRef.current?.export(exportFormat);
      const link = document.createElement("a");
      link.href = data;
      link.download = `思维导图.${exportFormat}`;
      link.click();
      setExportModalVisible(false);
      messageApi.success("导出成功");
    } catch (error) {
      messageApi.error("导出失败");
    }
  };

  const handleThemeChange = (value: string) => {
    setCurrentTheme(value);
    mindMapRef.current?.setTheme(value);
    const customConfig = customThemes[value as keyof typeof customThemes];
    if (customConfig) {
      mindMapRef.current?.setThemeConfig(customConfig);
    }
  };

  const toggleMousewheelAction = () => {
    if (!mindMapRef.current) return;
    setCurrentAction((prev) => (prev === "zoom" ? "move" : "zoom"));
    mindMapRef.current.updateConfig({
      mousewheelAction: currentAction === "zoom" ? "move" : "zoom",
    });
  };

  return (
    <Layout style={{ height: "100vh" }}>
      {contextHolder}
      <Header
        style={{
          background: token.colorBgContainer,
          padding: "0 16px",
          height: "auto",
          lineHeight: "1.5",
        }}
      >
        <div className="toolbar">
          <div className="toolbar-group">
            <Select
              value={currentLayout}
              onChange={setCurrentLayout}
              style={{ width: 120 }}
              options={layouts}
            />
            <Select
              value={currentTheme}
              onChange={handleThemeChange}
              style={{ width: 120 }}
              options={themes}
            />
            <Tooltip
              title={currentAction === "zoom" ? "切换为移动" : "切换为缩放"}
            >
              <Button
                icon={
                  currentAction === "zoom" ? (
                    <DragOutlined />
                  ) : (
                    <ZoomInOutlined />
                  )
                }
                onClick={toggleMousewheelAction}
              />
            </Tooltip>
          </div>
          <Divider type="vertical" className="toolbar-divider" />
          <div className="toolbar-group">
            <Tooltip title="撤销">
              <Button icon={<UndoOutlined />} onClick={handleUndo} />
            </Tooltip>
            <Tooltip title="重做">
              <Button icon={<RedoOutlined />} onClick={handleRedo} />
            </Tooltip>
          </div>
          <Divider type="vertical" className="toolbar-divider" />
          <div className="toolbar-group">
            <Tooltip title="保存">
              <Button icon={<SaveOutlined />} onClick={handleSave} />
            </Tooltip>
            <Tooltip title="导出">
              <Button
                icon={<ExportOutlined />}
                onClick={() => setExportModalVisible(true)}
              />
            </Tooltip>
          </div>
          <Divider type="vertical" className="toolbar-divider" />
          <div className="toolbar-group">
            <Tooltip title="插入图片">
              <Button icon={<PictureOutlined />} />
            </Tooltip>
            <ColorPicker>
              <Tooltip title="背景颜色">
                <Button icon={<BgColorsOutlined />} />
              </Tooltip>
            </ColorPicker>
          </div>
          <Divider type="vertical" className="toolbar-divider" />
          <div className="toolbar-group">
            <Tooltip title="字号">
              <Button icon={<FontSizeOutlined />} />
            </Tooltip>
            <Tooltip title="加粗">
              <Button icon={<BoldOutlined />} />
            </Tooltip>
            <Tooltip title="斜体">
              <Button icon={<ItalicOutlined />} />
            </Tooltip>
            <Tooltip title="下划线">
              <Button icon={<UnderlineOutlined />} />
            </Tooltip>
          </div>
          <Divider type="vertical" className="toolbar-divider" />
          <div className="toolbar-group">
            <Tooltip title="左对齐">
              <Button icon={<AlignLeftOutlined />} />
            </Tooltip>
            <Tooltip title="居中对齐">
              <Button icon={<AlignCenterOutlined />} />
            </Tooltip>
            <Tooltip title="右对齐">
              <Button icon={<AlignRightOutlined />} />
            </Tooltip>
          </div>
          <Divider type="vertical" className="toolbar-divider" />
          <div className="toolbar-group">
            <Tooltip title="分支">
              <Button icon={<BranchesOutlined />} />
            </Tooltip>
            <Tooltip title="节点">
              <Button icon={<NodeIndexOutlined />} />
            </Tooltip>
          </div>
          <div style={{ flex: 1 }} />
          <div className="toolbar-group">
            <Tooltip title="搜索">
              <Button icon={<SearchOutlined />} />
            </Tooltip>
            <Tooltip title="设置">
              <Button icon={<SettingOutlined />} />
            </Tooltip>
          </div>
        </div>
      </Header>
      <Content>
        <div id="mind-map-container" className="mind-map-container">
          <div
            ref={containerRef}
            style={{
              width: "100%",
              height: "calc(100vh - 64px)",
              position: "relative",
              overflow: "hidden",
            }}
          />
        </div>
      </Content>

      <Modal
        title="导出思维导图"
        open={exportModalVisible}
        onOk={handleExport}
        onCancel={() => setExportModalVisible(false)}
        okText="导出"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>选择导出格式：</div>
        <Select
          value={exportFormat}
          onChange={setExportFormat}
          style={{ width: "100%" }}
          options={exportFormats}
        />
      </Modal>
    </Layout>
  );
}

export default App;
